{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用Python实现了分割样本的函数sample_split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import numpy as np\n",
    "\n",
    "def sample_split(df, k):\n",
    "    \"\"\"\n",
    "    本函数实现对样本的分割\n",
    "    df:数据框对象\n",
    "    k:分割数量\n",
    "    return:返回类别数组\n",
    "    \"\"\"\n",
    "    t0 = np.array(range(df.shape[0]))%k\n",
    "    random.shuffle(t0)\n",
    "    return t0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里使用iris数据集，并建立Sepal.Length、Sepal.Width、Petal.Length对Petal.Width的线性回归模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.20726607,  0.22282854,  0.52408311]])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from sklearn import linear_model \n",
    "\n",
    "iris = pd.read_csv(\"http://image.cador.cn/data/iris.csv\")\n",
    "X = iris.loc[:,['Sepal.Length','Sepal.Width','Petal.Length']]\n",
    "y = iris.loc[:,['Petal.Width']]\n",
    "\n",
    "# 设置为10折交叉验证\n",
    "k=10\n",
    "parts = sample_split(iris, k)\n",
    "\n",
    "# 初始化最小均方误差 min_error\n",
    "min_error = 1000\n",
    "\n",
    "# 初始化最佳拟合结果 finalfit\n",
    "final_fit = None\n",
    "\n",
    "for i in range(k):\n",
    "    reg = linear_model.LinearRegression()\n",
    "    X_train = X.iloc[parts!=i,:]\n",
    "    y_train = y.iloc[parts!=i,:]\n",
    "    X_test = X.iloc[parts==i,:]\n",
    "    y_test = y.iloc[parts==i,:]\n",
    "    # 拟合线性回归模型\n",
    "    reg.fit(X_train, y_train)\n",
    "    # 计算均方误差\n",
    "    error = np.mean((y_test.values - reg.predict(X_test))**2)\n",
    "    if error < min_error:\n",
    "        min_error = error\n",
    "        final_fit = reg\n",
    "\n",
    "min_error\n",
    "# 0.014153864387035597\n",
    "\n",
    "final_fit.coef_\n",
    "# array([[-0.20013407,  0.21165518,  0.51669477]])\n",
    "\n",
    "# 2、使用一般方法得到的参数\n",
    "reg = linear_model.LinearRegression()\n",
    "reg.fit(X, y)\n",
    "reg.coef_\n",
    "# array([[-0.20726607,  0.22282854,  0.52408311]])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
